package com.heima.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.apache.lucene.search.BooleanQuery;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService searchService;
    /**
     * 文章搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //校验参数是否有数据  无则返回501
        if (dto == null) {
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //对分页数据进行修正
        if(dto.getPageNum() < 0  ){
            dto.setPageNum(0);
        }
        if (dto.getPageSize() <= 0){
            dto.setPageSize(10);
        }
        // 完成搜索
        SearchRequest searchRequest = new SearchRequest("app_info_article");

        //设置条件构建器对象
        SearchSourceBuilder sourceBulider = new SearchSourceBuilder();

        //创建一个复杂的bool查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        if (StringUtils.isBlank(dto.getSearchWords())) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords())
                    .field("title")
                    .field("content")
                    .defaultOperator(Operator.OR));

            //记录用户的关键词
            ApUser user = AppThreadLocalUtil.getUser();
            if (user != null) {
                searchService.insert(dto.getSearchWords() , user.getId());
            }

        }

        if (dto.getMinBehotTime() != null) {
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }
        //设置真正的查询条件
        sourceBulider.query(boolQuery);

        //设置高亮显示
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        highlighter.preTags("<font style='color: red; font-size: inherit;'>");
        highlighter.postTags("</font>");
        sourceBulider.highlighter(highlighter);

        //设置分页设置
        sourceBulider.from(dto.getFromIndex()).size(dto.getPageSize());
        searchRequest.source(sourceBulider);

        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
        //构建返回的参数
        SearchHit[] hits = search.getHits().getHits();
        List<Map>  list = new ArrayList<>(hits.length);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json ,Map.class);

            //解析高亮数据
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (highlightFields != null && highlightFields.size() >0) {
                Text[] titles = highlightFields.get("title").fragments();
                map.put("h_title",titles[0].toString());
            }else {
                map.put("h_title", map.get("title"));
            }
            list.add(map);
        }

        return ResponseResult.okResult(list);
    }
}
